<?php
/**
* 微信公众平台 PHP SDK
*
* @author CuiHao <cuihao871120@gmail.com>
*/
namespace Wechat;

//微信接口基础类
class Core
{
    protected $appid;
    protected $secret;

    public function __construct($appid,$secret)
    {
        $this->appid = $appid;
        $this->secret = $secret;
    }

    //发送POST请求（默认：HTTPS协议）
    protected function Post($url, $data, $method = 'HTTPS')
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($method === 'HTTPS') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        $data = curl_exec($ch);
        curl_close($ch);

        return json_decode($data,true);
    }

    //发送GET请求（默认：HTTPS协议）
    protected function Get($url, $method = 'HTTPS')
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($method === 'HTTPS') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        $data = curl_exec($ch);
        curl_close($ch);

        return json_decode($data,true);
    }

    //获取Token值
    protected function GetAccessToken(){
        $grant_type = "client_credential";
        $appid = $this->appid;
        $secret = $this->secret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type={$grant_type}&appid={$appid}&secret={$secret}";
        $result = $this->Get($url);
        if (isset($result['access_token'])) {
            return $result['access_token'];
        } else {
            return false;
        }
    }
}